package com.zhentao.controller;

import com.zhentao.annotation.OperationLog;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/dataLog")
@CrossOrigin
public class dataLogController {

    @Autowired
    private CustomsDataLogService customsDataLogService;
    
    @Autowired
    private SysUserService sysUserService;

    /**
     * 获取日志列表
     */
    @OperationLog(bizModule = 3, bizType = 5, description = "查询操作日志列表", recordParams = false)
    @GetMapping("/list")
    public Map<String, Object> getLogList(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer size,
                                        @RequestParam(required = false) Integer bizModule,
                                        @RequestParam(required = false) Integer bizType,
                                        @RequestParam(required = false) String operator,
                                        @RequestParam(required = false) String startTime,
                                        @RequestParam(required = false) String endTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 构建查询条件
            Map<String, Object> queryParams = new HashMap<>();
            if (bizModule != null) {
                queryParams.put("bizModule", bizModule);
            }
            if (bizType != null) {
                queryParams.put("bizType", bizType);
            }
            if (operator != null && !operator.isEmpty()) {
                queryParams.put("operator", operator);
            }
            if (startTime != null && !startTime.isEmpty()) {
                queryParams.put("startTime", startTime);
            }
            if (endTime != null && !endTime.isEmpty()) {
                queryParams.put("endTime", endTime);
            }
            
            // 分页查询日志数据
            List<CustomsDataLog> logList = customsDataLogService.getPageList(page, size, queryParams);
            
            // 关联查询操作人信息
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (CustomsDataLog log : logList) {
                Map<String, Object> item = new HashMap<>();
                item.put("log", log);
                
                // 获取操作人信息
                if (log.getOperator() != null && !log.getOperator().isEmpty()) {
                    try {
                        Integer userId = Integer.parseInt(log.getOperator());
                        SysUser user = sysUserService.getById(userId);
                        item.put("operatorInfo", user);
                    } catch (NumberFormatException e) {
                        // 如果不是数字，可能是系统操作
                        item.put("operatorInfo", null);
                    }
                }
                
                resultList.add(item);
            }
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", resultList);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取日志详情
     */
    @OperationLog(bizModule = 3, bizType = 5, description = "查询操作日志详情")
    @GetMapping("/detail/{id}")
    public Map<String, Object> getLogDetail(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            CustomsDataLog log = customsDataLogService.getById(id);
            if (log == null) {
                result.put("code", 404);
                result.put("message", "日志记录不存在");
                return result;
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("log", log);
            
            // 获取操作人信息
            if (log.getOperator() != null && !log.getOperator().isEmpty()) {
                try {
                    Integer userId = Integer.parseInt(log.getOperator());
                    SysUser user = sysUserService.getById(userId);
                    data.put("operatorInfo", user);
                } catch (NumberFormatException e) {
                    data.put("operatorInfo", null);
                }
            }
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", data);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取模块统计信息
     */
    @OperationLog(bizModule = 3, bizType = 7, description = "获取模块统计信息", recordParams = false)
    @GetMapping("/moduleStatistics")
    public Map<String, Object> getModuleStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 按业务模块统计
            statistics.put("dataCollection", customsDataLogService.countByModule(1)); // 数据采集入库
            statistics.put("exceptionManagement", customsDataLogService.countByModule(2)); // 数据异常管理
            statistics.put("dataQuery", customsDataLogService.countByModule(3)); // 数据应用查询
            statistics.put("keywordValidation", customsDataLogService.countByModule(4)); // 特征词校验
            statistics.put("storageStatistics", customsDataLogService.countByModule(5)); // 入库统计
            statistics.put("logSummary", customsDataLogService.countByModule(6)); // 数据采集日志汇总
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", statistics);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取操作类型统计信息
     */
    @OperationLog(bizModule = 3, bizType = 7, description = "获取操作类型统计信息", recordParams = false)
    @GetMapping("/typeStatistics")
    public Map<String, Object> getTypeStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 按操作类型统计
            statistics.put("collection", customsDataLogService.countByType(1)); // 采集
            statistics.put("storage", customsDataLogService.countByType(2)); // 入库
            statistics.put("exceptionMark", customsDataLogService.countByType(3)); // 异常标记
            statistics.put("exceptionFix", customsDataLogService.countByType(4)); // 异常修复
            statistics.put("dataQuery", customsDataLogService.countByType(5)); // 数据查询
            statistics.put("keywordValidation", customsDataLogService.countByType(6)); // 特征词校验
            statistics.put("statisticsCalc", customsDataLogService.countByType(7)); // 统计计算
            statistics.put("logQuery", customsDataLogService.countByType(8)); // 日志查询
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", statistics);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取操作人员统计信息
     */
    @OperationLog(bizModule = 3, bizType = 7, description = "获取操作人员统计信息", recordParams = false)
    @GetMapping("/operatorStatistics")
    public Map<String, Object> getOperatorStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Map<String, Object>> operatorStats = customsDataLogService.getOperatorStatistics();
            
            // 补充操作人员信息
            for (Map<String, Object> stat : operatorStats) {
                String operator = (String) stat.get("operator");
                if (operator != null && !operator.isEmpty()) {
                    try {
                        Integer userId = Integer.parseInt(operator);
                        SysUser user = sysUserService.getById(userId);
                        if (user != null) {
                            stat.put("operatorName", user.getRealName());
                            stat.put("operatorInfo", user);
                        }
                    } catch (NumberFormatException e) {
                        stat.put("operatorName", operator);
                        stat.put("operatorInfo", null);
                    }
                }
            }
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", operatorStats);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取日志趋势分析
     */
    @OperationLog(bizModule = 3, bizType = 7, description = "获取日志趋势分析", recordParams = false)
    @GetMapping("/trend")
    public Map<String, Object> getLogTrend(@RequestParam String startTime,
                                         @RequestParam String endTime,
                                         @RequestParam(defaultValue = "day") String granularity) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Map<String, Object>> trendData = customsDataLogService.getLogTrend(startTime, endTime, granularity);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", trendData);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 导出日志
     */
    @OperationLog(bizModule = 3, bizType = 6, description = "导出操作日志")
    @PostMapping("/export")
    public Map<String, Object> exportLogs(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer bizModule = (Integer) params.get("bizModule");
            Integer bizType = (Integer) params.get("bizType");
            String operator = (String) params.get("operator");
            String startTime = (String) params.get("startTime");
            String endTime = (String) params.get("endTime");
            
            // 构建查询条件
            Map<String, Object> queryParams = new HashMap<>();
            if (bizModule != null) {
                queryParams.put("bizModule", bizModule);
            }
            if (bizType != null) {
                queryParams.put("bizType", bizType);
            }
            if (operator != null && !operator.isEmpty()) {
                queryParams.put("operator", operator);
            }
            if (startTime != null && !startTime.isEmpty()) {
                queryParams.put("startTime", startTime);
            }
            if (endTime != null && !endTime.isEmpty()) {
                queryParams.put("endTime", endTime);
            }
            
            // 查询所有符合条件的日志
            List<CustomsDataLog> logList = customsDataLogService.getAllByParams(queryParams);
            
            // 记录导出操作日志
            CustomsDataLog exportLog = new CustomsDataLog();
            exportLog.setBizModule(6); // 数据采集日志汇总
            exportLog.setBizType(8); // 日志查询
            exportLog.setOperationDesc("导出日志数据");
            exportLog.setRelationId("EXPORT_" + System.currentTimeMillis());
            exportLog.setOperator(params.get("currentUserId").toString());
            exportLog.setOperateTime(new Date());
            exportLog.setRequestParams("导出条件：" + queryParams.toString());
            exportLog.setResponseResult("成功，导出" + logList.size() + "条记录");
            customsDataLogService.save(exportLog);
            
            result.put("code", 200);
            result.put("message", "导出成功");
            result.put("data", logList);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 清理历史日志
     */
    @OperationLog(bizModule = 3, bizType = 8, description = "清理历史操作日志")
    @PostMapping("/cleanup")
    public Map<String, Object> cleanupLogs(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            String beforeDate = (String) params.get("beforeDate");
            Integer userId = (Integer) params.get("userId");
            
            if (beforeDate == null || beforeDate.isEmpty()) {
                result.put("code", 400);
                result.put("message", "请指定清理日期");
                return result;
            }
            
            // 执行清理操作
            int cleanupCount = customsDataLogService.cleanupBefore(beforeDate);
            
            // 记录清理操作日志
            CustomsDataLog cleanupLog = new CustomsDataLog();
            cleanupLog.setBizModule(6);
            cleanupLog.setBizType(8);
            cleanupLog.setOperationDesc("清理历史日志");
            cleanupLog.setRelationId("CLEANUP_" + System.currentTimeMillis());
            cleanupLog.setOperator(userId.toString());
            cleanupLog.setOperateTime(new Date());
            cleanupLog.setRequestParams("清理" + beforeDate + "之前的日志");
            cleanupLog.setResponseResult("成功，清理" + cleanupCount + "条记录");
            customsDataLogService.save(cleanupLog);
            
            result.put("code", 200);
            result.put("message", "清理完成，共清理" + cleanupCount + "条历史日志");
            result.put("data", cleanupCount);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }
}
